<template>
  <div class="unified-fuel-management">
    <!-- 标签页导航 -->
    <div class="tabs-container">
      <div class="tabs">
        <button
          v-for="tab in tabs"
          :key="tab.id"
          @click="activeTab = tab.id"
          :class="['tab-button', { active: activeTab === tab.id }]"
        >
          <span class="tab-icon">{{ tab.icon }}</span>
          <span class="tab-label">{{ tab.label }}</span>
        </button>
      </div>
    </div>

    <!-- 标签页内容 -->
    <div class="tab-content">
      <!-- 车辆管理标签页 -->
      <div v-if="activeTab === 'vehicles'" class="tab-panel">
        <div class="vehicles-grid">
          <div
            v-for="vehicle in vehicles"
            :key="vehicle.id"
            class="vehicle-card"
            :class="{ inactive: !vehicle.is_active }"
          >
            <div class="vehicle-header">
              <div class="vehicle-info">
                <h3 class="vehicle-name">{{ vehicle.name }}</h3>
                <p class="vehicle-model">
                  {{ vehicle.brand }} {{ vehicle.model }}
                </p>
                <div class="vehicle-badges">
                  <span class="license-plate">{{ vehicle.license_plate }}</span>
                  <span v-if="vehicle.year" class="year-badge">
                    {{ vehicle.year }}年
                  </span>
                  <span
                    :class="[
                      'status-badge',
                      vehicle.is_active ? 'active' : 'inactive',
                    ]"
                  >
                    {{ vehicle.is_active ? "使用中" : "已停用" }}
                  </span>
                </div>
              </div>
              <div class="vehicle-actions">
                <button
                  @click="editVehicle(vehicle)"
                  class="action-button edit"
                  title="编辑"
                >
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <path
                      d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"
                    />
                    <path
                      d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"
                    />
                  </svg>
                </button>
                <button
                  @click="deleteVehicle(vehicle)"
                  class="action-button delete"
                  title="删除"
                >
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <path
                      d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6h14zM10 11v6M14 11v6"
                    />
                  </svg>
                </button>
              </div>
            </div>

            <div class="vehicle-details">
              <div class="detail-item">
                <span class="detail-label">创建时间:</span>
                <span class="detail-value">{{
                  formatDate(vehicle.created_at)
                }}</span>
              </div>
              <div v-if="vehicle.notes" class="detail-item">
                <span class="detail-label">备注:</span>
                <span class="detail-value">{{ vehicle.notes }}</span>
              </div>
            </div>
          </div>

          <!-- 添加车辆卡片 -->
          <div
            class="vehicle-card add-vehicle-card"
            @click="showAddVehicleModal = true"
          >
            <div class="add-vehicle-content">
              <svg
                width="48"
                height="48"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              >
                <line x1="12" y1="5" x2="12" y2="19"></line>
                <line x1="5" y1="12" x2="19" y2="12"></line>
              </svg>
              <span class="add-vehicle-text">添加车辆</span>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="vehicles.length === 0 && !loading" class="empty-state">
          <svg
            width="64"
            height="64"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1"
          >
            <path
              d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5Z"
            />
            <path d="M12 5L8 21l4-7 4 7-4-16Z" />
          </svg>
          <p>暂无车辆信息</p>
          <button @click="showAddVehicleModal = true" class="add-button">
            添加第一辆车
          </button>
        </div>
      </div>

      <!-- 加油记录标签页 -->
      <div v-if="activeTab === 'records'" class="tab-panel">
        <!-- 油耗统计卡片 - 放在最上面 -->
        <div class="fuel-stats-section">
          <div class="section-header">
            <h3>油耗统计</h3>
            <button @click="showVehicleManagementModal = true" class="manage-vehicles-btn">
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              >
                <path
                  d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5Z"
                />
                <path d="M12 5L8 21l4-7 4 7-4-16Z" />
              </svg>
              管理车辆
            </button>
          </div>
          
          <div class="stats-cards">
            <div class="stat-card">
              <div class="stat-icon">⛽</div>
              <div class="stat-content">
                <div class="stat-label">总加油量</div>
                <div class="stat-value">{{ totalFuelAmount.toFixed(2) }} 升</div>
              </div>
            </div>

            <div class="stat-card">
              <div class="stat-icon">💰</div>
              <div class="stat-content">
                <div class="stat-label">总费用</div>
                <div class="stat-value">¥{{ totalFuelCost.toFixed(2) }}</div>
              </div>
            </div>

            <div class="stat-card">
              <div class="stat-icon">📊</div>
              <div class="stat-content">
                <div class="stat-label">平均油耗</div>
                <div class="stat-value">
                  {{ avgFuelConsumption.toFixed(2) }} L/100km
                </div>
              </div>
            </div>

            <div class="stat-card">
              <div class="stat-icon">🚗</div>
              <div class="stat-content">
                <div class="stat-label">记录数量</div>
                <div class="stat-value">{{ fuelRecords.length }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 详细油耗统计折叠区域 -->
        <div class="detailed-stats-section">
          <div class="collapsible-header" @click="showDetailedStats = !showDetailedStats">
            <h3>详细油耗统计</h3>
            <div class="collapse-toggle">
              <span class="toggle-text">{{ showDetailedStats ? '收起' : '展开' }}</span>
              <svg 
                class="collapse-icon" 
                :class="{ 'collapsed': !showDetailedStats }"
                width="16" 
                height="16" 
                viewBox="0 0 24 24" 
                fill="none" 
                stroke="currentColor" 
                stroke-width="2"
              >
                <polyline points="6 9 12 15 18 9"></polyline>
              </svg>
            </div>
          </div>

          <div v-show="showDetailedStats" class="detailed-stats-content">
            <!-- 详细统计筛选 -->
            <div class="filter-section">
              <div class="filter-row">
                <div class="filter-group">
                  <label for="detailed-stats-vehicle-filter">车辆</label>
                  <select
                    id="detailed-stats-vehicle-filter"
                    v-model="statsFilters.vehicle_id"
                    @change="fetchStats"
                  >
                    <option value="">全部车辆</option>
                    <option
                      v-for="vehicle in vehicles"
                      :key="vehicle.id"
                      :value="vehicle.id"
                    >
                      {{ vehicle.name }}
                    </option>
                  </select>
                </div>

                <div class="filter-group">
                  <label for="detailed-stats-start-date">开始日期</label>
                  <input
                    id="detailed-stats-start-date"
                    v-model="statsFilters.start_date"
                    type="date"
                    @change="fetchStats"
                  />
                </div>

                <div class="filter-group">
                  <label for="detailed-stats-end-date">结束日期</label>
                  <input
                    id="detailed-stats-end-date"
                    v-model="statsFilters.end_date"
                    type="date"
                    @change="fetchStats"
                  />
                </div>
              </div>
            </div>

            <!-- 主要统计卡片 -->
            <div v-if="fuelStats" class="main-stats">
              <div class="stats-grid">
                <div class="stat-card primary">
                  <div class="stat-icon">📊</div>
                  <div class="stat-content">
                    <div class="stat-label">平均油耗</div>
                    <div class="stat-value">
                      {{ fuelStats.avg_fuel_consumption.toFixed(2) }}
                      <span class="unit">L/100km</span>
                    </div>
                  </div>
                </div>

                <div class="stat-card success">
                  <div class="stat-icon">💰</div>
                  <div class="stat-content">
                    <div class="stat-label">总加油费用</div>
                    <div class="stat-value">
                      ¥{{ fuelStats.total_fuel_cost.toFixed(2) }}
                    </div>
                  </div>
                </div>

                <div class="stat-card info">
                  <div class="stat-icon">⛽</div>
                  <div class="stat-content">
                    <div class="stat-label">总加油量</div>
                    <div class="stat-value">
                      {{ fuelStats.total_fuel_amount.toFixed(2) }}
                      <span class="unit">升</span>
                    </div>
                  </div>
                </div>

                <div class="stat-card warning">
                  <div class="stat-icon">🛣️</div>
                  <div class="stat-content">
                    <div class="stat-label">总行驶里程</div>
                    <div class="stat-value">
                      {{ fuelStats.total_distance.toFixed(0) }}
                      <span class="unit">km</span>
                    </div>
                  </div>
                </div>
              </div>

              <div class="stats-grid secondary">
                <div class="stat-card">
                  <div class="stat-icon">📝</div>
                  <div class="stat-content">
                    <div class="stat-label">记录数量</div>
                    <div class="stat-value">{{ fuelStats.record_count }}</div>
                  </div>
                </div>

                <div class="stat-card">
                  <div class="stat-icon">💵</div>
                  <div class="stat-content">
                    <div class="stat-label">平均油价</div>
                    <div class="stat-value">
                      ¥{{ fuelStats.avg_fuel_price.toFixed(2) }}
                      <span class="unit">/升</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else-if="!statsLoading && !fuelStats" class="empty-state">
              <svg
                width="64"
                height="64"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="1"
              >
                <path
                  d="M9 11H3v10h6V11zm4-7H7v17h6V4zm4 3h-6v14h6V7zm4-6h-6v20h6V1z"
                />
                <path d="M9 2v2m6-2v2m6-2v2" />
              </svg>
              <p>暂无统计数据</p>
              <p class="empty-hint">请先添加加油记录以查看统计信息</p>
            </div>

            <!-- 加载状态 -->
            <div v-else-if="statsLoading" class="loading-state">
              <div class="loading-spinner"></div>
              <p>加载统计数据中...</p>
            </div>

            <!-- 费用汇总 -->
            <div v-if="costSummary" class="cost-summary-section">
              <h3>费用汇总</h3>
              <div class="cost-summary-grid">
                <div class="cost-item">
                  <span class="cost-label">总费用:</span>
                  <span class="cost-value"
                    >¥{{ costSummary.total_cost?.toFixed(2) || "0.00" }}</span
                  >
                </div>
                <div class="cost-item">
                  <span class="cost-label">月均费用:</span>
                  <span class="cost-value"
                    >¥{{ costSummary.monthly_average?.toFixed(2) || "0.00" }}</span
                  >
                </div>
                <div class="cost-item">
                  <span class="cost-label">日均费用:</span>
                  <span class="cost-value"
                    >¥{{ costSummary.daily_average?.toFixed(2) || "0.00" }}</span
                  >
                </div>
              </div>
            </div>

            <!-- 车辆对比 -->
            <div
              v-if="vehiclesWithStats.length > 0"
              class="vehicle-comparison-section"
            >
              <h3>车辆对比</h3>
              <div class="vehicle-comparison-grid">
                <div
                  v-for="vehicleWithStats in vehiclesWithStats"
                  :key="vehicleWithStats.vehicle.id"
                  class="vehicle-comparison-card"
                >
                  <div class="vehicle-header">
                    <h4>{{ vehicleWithStats.vehicle.name }}</h4>
                    <span
                      class="vehicle-status"
                      :class="{ active: vehicleWithStats.vehicle.is_active }"
                    >
                      {{ vehicleWithStats.vehicle.is_active ? "使用中" : "已停用" }}
                    </span>
                  </div>

                  <div class="vehicle-stats">
                    <div class="vehicle-stat-item">
                      <span class="stat-label">油耗</span>
                      <span class="stat-value">
                        {{
                          vehicleWithStats.fuel_stats?.avg_fuel_consumption?.toFixed(
                            2,
                          ) || "N/A"
                        }}
                        L/100km
                      </span>
                    </div>
                    <div class="vehicle-stat-item">
                      <span class="stat-label">总费用</span>
                      <span class="stat-value">
                        ¥{{
                          vehicleWithStats.fuel_stats?.total_fuel_cost?.toFixed(
                            2,
                          ) || "0.00"
                        }}
                      </span>
                    </div>
                    <div class="vehicle-stat-item">
                      <span class="stat-label">记录数</span>
                      <span class="stat-value">
                        {{ vehicleWithStats.fuel_stats?.record_count || 0 }}
                      </span>
                    </div>
                  </div>

                  <div
                    v-if="vehicleWithStats.latest_fuel_record"
                    class="latest-record"
                  >
                    <div class="latest-record-header">
                      <span class="latest-label">最新记录</span>
                      <span class="latest-date">{{
                        formatDate(vehicleWithStats.latest_fuel_record.refuel_date)
                      }}</span>
                    </div>
                    <div class="latest-record-details">
                      <span
                        >{{
                          vehicleWithStats.latest_fuel_record.fuel_amount.toFixed(
                            2,
                          )
                        }}升</span
                      >
                      <span
                        >¥{{
                          vehicleWithStats.latest_fuel_record.fuel_cost.toFixed(2)
                        }}</span
                      >
                      <span
                        >{{
                          vehicleWithStats.latest_fuel_record.current_mileage.toFixed(
                            0,
                          )
                        }}km</span
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 趋势图表 -->
            <div
              v-if="fuelStats && fuelStats.record_count > 0"
              class="trend-section"
            >
              <h3>油耗趋势</h3>
              <div class="trend-chart">
                <div class="chart-placeholder">
                  <svg width="100%" height="200" viewBox="0 0 400 200">
                    <!-- 简单的图表占位符 -->
                    <rect
                      x="50"
                      y="20"
                      width="300"
                      height="160"
                      fill="none"
                      stroke="var(--el-border-color)"
                      stroke-width="2"
                      rx="8"
                    />
                    <text
                      x="200"
                      y="100"
                      text-anchor="middle"
                      fill="var(--el-text-color-secondary)"
                      font-size="14"
                    >
                      图表功能开发中...
                    </text>
                  </svg>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 筛选和搜索栏 -->
        <div class="filter-section">
          <div class="filter-row">
            <div class="filter-group">
              <label for="vehicle-filter">车辆</label>
              <select
                id="vehicle-filter"
                v-model="filters.vehicle_id"
                @change="fetchRecords"
              >
                <option value="">全部车辆</option>
                <option
                  v-for="vehicle in vehicles"
                  :key="vehicle.id"
                  :value="vehicle.id"
                >
                  {{ vehicle.name }}
                </option>
              </select>
            </div>

            <div class="filter-group">
              <label for="station-filter">加油站类型</label>
              <select
                id="station-filter"
                v-model="filters.gas_station_type"
                @change="fetchRecords"
              >
                <option value="">全部类型</option>
                <option
                  v-for="type in gasStationTypes"
                  :key="type"
                  :value="type"
                >
                  {{ type }}
                </option>
              </select>
            </div>

            <div class="filter-group">
              <label for="start-date">开始日期</label>
              <input
                id="start-date"
                v-model="filters.start_date"
                type="date"
                @change="fetchRecords"
              />
            </div>

            <div class="filter-group">
              <label for="end-date">结束日期</label>
              <input
                id="end-date"
                v-model="filters.end_date"
                type="date"
                @change="fetchRecords"
              />
            </div>
          </div>
        </div>

        <!-- 加油记录列表 -->
        <div class="records-section">
          <div class="section-header">
            <h3>加油记录</h3>
            <button @click="showAddRecordModal = true" class="add-button">
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              >
                <line x1="12" y1="5" x2="12" y2="19"></line>
                <line x1="5" y1="12" x2="19" y2="12"></line>
              </svg>
              添加记录
            </button>
          </div>

          <div v-if="loading && fuelRecords.length === 0" class="loading-state">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
          </div>

          <div v-else-if="fuelRecords.length === 0" class="empty-state">
            <svg
              width="64"
              height="64"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1"
            >
              <path
                d="M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z"
              />
              <path d="M12 8v4M12 16h.01" />
            </svg>
            <p>暂无加油记录</p>
            <button @click="showAddRecordModal = true" class="add-button">
              添加第一条记录
            </button>
          </div>

          <div v-else class="records-list">
            <div
              v-for="record in fuelRecords"
              :key="record.id"
              class="record-card"
            >
              <div class="record-header">
                <div class="record-vehicle">
                  <span class="vehicle-name">{{ record.vehicle_name }}</span>
                  <span class="record-date">{{
                    formatDate(record.refuel_date)
                  }}</span>
                </div>
                <div class="record-actions">
                  <button
                    @click="editRecord(record)"
                    class="action-button edit"
                  >
                    <svg
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                    >
                      <path
                        d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"
                      />
                      <path
                        d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"
                      />
                    </svg>
                  </button>
                  <button
                    @click="deleteRecord(record)"
                    class="action-button delete"
                  >
                    <svg
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                    >
                      <path
                        d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6h14zM10 11v6M14 11v6"
                      />
                    </svg>
                  </button>
                </div>
              </div>

              <div class="record-details">
                <div class="detail-grid">
                  <div class="detail-item">
                    <span class="detail-label">加油量</span>
                    <span class="detail-value"
                      >{{ record.fuel_amount.toFixed(2) }} 升</span
                    >
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">金额</span>
                    <span class="detail-value"
                      >¥{{ record.fuel_cost.toFixed(2) }}</span
                    >
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">油价</span>
                    <span class="detail-value"
                      >¥{{ record.fuel_price.toFixed(2) }}/升</span
                    >
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">里程</span>
                    <span class="detail-value"
                      >{{ record.current_mileage.toFixed(0) }} km</span
                    >
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">加油站</span>
                    <span class="detail-value">{{
                      record.gas_station_type
                    }}</span>
                  </div>
                  <div v-if="record.fuel_consumption" class="detail-item">
                    <span class="detail-label">油耗</span>
                    <span class="detail-value"
                      >{{ record.fuel_consumption.toFixed(2) }} L/100km</span
                    >
                  </div>
                </div>
                <div v-if="record.notes" class="record-notes">
                  <span class="detail-label">备注:</span>
                  <span class="detail-value">{{ record.notes }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      </div>

    <!-- 车辆管理模态框 -->
    <div
      v-if="showAddVehicleModal || showEditVehicleModal"
      class="modal-overlay"
      @click.self="closeVehicleModals"
    >
      <div class="modal glass-effect">
        <div class="modal-header">
          <h3>{{ showAddVehicleModal ? "添加车辆" : "编辑车辆" }}</h3>
          <button @click="closeVehicleModals" class="close-button">
            <svg
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
            >
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <form @submit.prevent="handleVehicleSubmit" class="vehicle-form">
          <div class="form-group">
            <label for="name">车辆名称 *</label>
            <input
              id="name"
              v-model="vehicleFormData.name"
              type="text"
              required
              placeholder="例如：我的私家车"
              :class="{ error: vehicleErrors.name }"
            />
            <span v-if="vehicleErrors.name" class="error-message">{{
              vehicleErrors.name
            }}</span>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="brand">品牌 *</label>
              <input
                id="brand"
                v-model="vehicleFormData.brand"
                type="text"
                required
                placeholder="例如：丰田"
                :class="{ error: vehicleErrors.brand }"
              />
              <span v-if="vehicleErrors.brand" class="error-message">{{
                vehicleErrors.brand
              }}</span>
            </div>

            <div class="form-group">
              <label for="model">型号 *</label>
              <input
                id="model"
                v-model="vehicleFormData.model"
                type="text"
                required
                placeholder="例如：卡罗拉"
                :class="{ error: vehicleErrors.model }"
              />
              <span v-if="vehicleErrors.model" class="error-message">{{
                vehicleErrors.model
              }}</span>
            </div>
          </div>

          <div class="form-group">
            <label for="license_plate">车牌号 *</label>
            <input
              id="license_plate"
              v-model="vehicleFormData.license_plate"
              type="text"
              required
              placeholder="例如：京A12345"
              :class="{ error: vehicleErrors.license_plate }"
            />
            <span v-if="vehicleErrors.license_plate" class="error-message">{{
              vehicleErrors.license_plate
            }}</span>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="year">年份</label>
              <input
                id="year"
                v-model="vehicleFormData.year"
                type="number"
                min="1900"
                max="2100"
                placeholder="例如：2020"
              />
            </div>

            <div class="form-group">
              <label for="is_active">状态</label>
              <select id="is_active" v-model="vehicleFormData.is_active">
                <option :value="true">使用中</option>
                <option :value="false">已停用</option>
              </select>
            </div>
          </div>

          <div class="form-group">
            <label for="notes">备注</label>
            <textarea
              id="notes"
              v-model="vehicleFormData.notes"
              rows="3"
              placeholder="请输入备注信息（可选）"
            ></textarea>
          </div>

          <div class="form-actions">
            <button
              type="button"
              @click="closeVehicleModals"
              class="cancel-button"
            >
              取消
            </button>
            <button type="submit" class="submit-button" :disabled="loading">
              {{
                loading ? "保存中..." : showAddVehicleModal ? "添加" : "保存"
              }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 加油记录模态框 -->
    <div
      v-if="showAddRecordModal || showEditRecordModal"
      class="modal-overlay"
      @click.self="closeRecordModals"
    >
      <div class="modal glass-effect">
        <div class="modal-header">
          <h3>{{ showAddRecordModal ? "添加加油记录" : "编辑加油记录" }}</h3>
          <button @click="closeRecordModals" class="close-button">
            <svg
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
            >
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <form @submit.prevent="handleRecordSubmit" class="record-form">
          <div class="form-group">
            <label for="vehicle_id">车辆 *</label>
            <select
              id="vehicle_id"
              v-model="recordFormData.vehicle_id"
              required
              placeholder="请选择车辆"
              :class="{ error: recordErrors.vehicle_id }"
            >
              <option
                v-for="vehicle in vehicles"
                :key="vehicle.id"
                :value="vehicle.id"
              >
                {{ vehicle.name }}
              </option>
            </select>
            <span v-if="recordErrors.vehicle_id" class="error-message">{{
              recordErrors.vehicle_id
            }}</span>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="current_mileage">当前里程 (km) *</label>
              <input
                id="current_mileage"
                v-model="recordFormData.current_mileage"
                type="number"
                step="0.1"
                min="0"
                required
                placeholder="例如：15000.5"
                :class="{ error: recordErrors.current_mileage }"
              />
              <span v-if="recordErrors.current_mileage" class="error-message">{{
                recordErrors.current_mileage
              }}</span>
            </div>

            <div class="form-group">
              <label for="fuel_amount">加油量 (升) *</label>
              <input
                id="fuel_amount"
                v-model.number="recordFormData.fuel_amount"
                @input="
                  handleFuelAmountChange(
                    ($event.target as HTMLInputElement).value,
                  )
                "
                type="number"
                step="0.01"
                min="0"
                required
                placeholder="例如：40.5"
                :class="{ error: recordErrors.fuel_amount }"
              />
              <span v-if="recordErrors.fuel_amount" class="error-message">{{
                recordErrors.fuel_amount
              }}</span>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="fuel_cost">加油金额 (元) *</label>
              <input
                id="fuel_cost"
                v-model.number="recordFormData.fuel_cost"
                @input="
                  handleFuelCostChange(
                    ($event.target as HTMLInputElement).value,
                  )
                "
                type="number"
                step="0.01"
                min="0"
                required
                placeholder="例如：300.5"
                :class="{ error: recordErrors.fuel_cost }"
              />
              <span v-if="recordErrors.fuel_cost" class="error-message">{{
                recordErrors.fuel_cost
              }}</span>
            </div>

            <div class="form-group">
              <label for="fuel_price">油价 (元/升) *</label>
              <input
                id="fuel_price"
                v-model.number="recordFormData.fuel_price"
                @input="
                  handleFuelPriceChange(
                    ($event.target as HTMLInputElement).value,
                  )
                "
                type="number"
                step="0.01"
                min="0"
                required
                placeholder="例如：7.5"
                :class="{ error: recordErrors.fuel_price }"
              />
              <span v-if="recordErrors.fuel_price" class="error-message">{{
                recordErrors.fuel_price
              }}</span>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="gas_station_type">加油站类型 *</label>
              <select
                id="gas_station_type"
                v-model="recordFormData.gas_station_type"
                required
                placeholder="请选择加油站类型"
                :class="{ error: recordErrors.gas_station_type }"
              >
                <option
                  v-for="type in gasStationTypes"
                  :key="type"
                  :value="type"
                >
                  {{ type }}
                </option>
              </select>
              <span
                v-if="recordErrors.gas_station_type"
                class="error-message"
                >{{ recordErrors.gas_station_type }}</span
              >
            </div>

            <div class="form-group">
              <label for="refuel_date">加油日期 *</label>
              <input
                id="refuel_date"
                v-model="recordFormData.refuel_date"
                type="datetime-local"
                required
                :class="{ error: recordErrors.refuel_date }"
              />
              <span v-if="recordErrors.refuel_date" class="error-message">{{
                recordErrors.refuel_date
              }}</span>
            </div>
          </div>

          <div class="form-group">
            <label for="notes">备注</label>
            <textarea
              id="notes"
              v-model="recordFormData.notes"
              rows="3"
              placeholder="请输入备注信息（可选）"
            ></textarea>
          </div>

          <div class="form-actions">
            <button
              type="button"
              @click="closeRecordModals"
              class="cancel-button"
            >
              取消
            </button>
            <button type="submit" class="submit-button" :disabled="loading">
              {{ loading ? "保存中..." : showAddRecordModal ? "添加" : "保存" }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div
      v-if="showDeleteModal"
      class="modal-overlay"
      @click.self="showDeleteModal = false"
    >
      <div class="modal glass-effect delete-modal">
        <div class="modal-header">
          <h3>确认删除</h3>
          <button @click="showDeleteModal = false" class="close-button">
            <svg
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
            >
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div class="delete-content">
          <svg
            width="48"
            height="48"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1"
          >
            <path
              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
            />
          </svg>
          <p>
            确定要删除{{ deleteTarget === "vehicle" ? "车辆" : "加油记录" }} "{{
              deleteTargetName
            }}" 吗？
          </p>
          <p class="delete-warning">此操作不可撤销。</p>
        </div>

        <div class="delete-actions">
          <button @click="showDeleteModal = false" class="cancel-button">
            取消
          </button>
          <button
            @click="confirmDelete"
            class="delete-button"
            :disabled="loading"
          >
            {{ loading ? "删除中..." : "确认删除" }}
          </button>
        </div>
      </div>
    </div>

    <!-- 车辆管理弹窗 -->
    <div
      v-if="showVehicleManagementModal"
      class="modal-overlay"
      @click.self="showVehicleManagementModal = false"
    >
      <div class="modal vehicle-management-modal glass-effect">
        <div class="modal-header">
          <h3>车辆管理</h3>
          <button @click="showVehicleManagementModal = false" class="close-button">
            <svg
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
            >
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div class="vehicle-management-content">
          <!-- 车辆列表 -->
          <div class="vehicles-list">
            <div
              v-for="vehicle in vehicles"
              :key="vehicle.id"
              class="vehicle-management-item"
              :class="{ inactive: !vehicle.is_active }"
            >
              <div class="vehicle-info">
                <div class="vehicle-name">{{ vehicle.name }}</div>
                <div class="vehicle-details">
                  <span class="vehicle-model">{{ vehicle.brand }} {{ vehicle.model }}</span>
                  <span class="vehicle-license">{{ vehicle.license_plate }}</span>
                  <span
                    :class="[
                      'status-badge',
                      vehicle.is_active ? 'active' : 'inactive',
                    ]"
                  >
                    {{ vehicle.is_active ? "使用中" : "已停用" }}
                  </span>
                </div>
              </div>
              <div class="vehicle-actions">
                <button
                  @click="editVehicle(vehicle)"
                  class="action-button edit"
                  title="编辑"
                >
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <path
                      d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"
                    />
                    <path
                      d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"
                    />
                  </svg>
                </button>
                <button
                  @click="deleteVehicle(vehicle)"
                  class="action-button delete"
                  title="删除"
                >
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <path
                      d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6h14zM10 11v6M14 11v6"
                    />
                  </svg>
                </button>
              </div>
            </div>

            <!-- 添加车辆按钮 -->
            <div
              class="vehicle-management-item add-vehicle-item"
              @click="showAddVehicleModal = true"
            >
              <div class="add-vehicle-content">
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <line x1="12" y1="5" x2="12" y2="19"></line>
                  <line x1="5" y1="12" x2="19" y2="12"></line>
                </svg>
                <span>添加车辆</span>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="vehicles.length === 0" class="empty-state">
            <svg
              width="64"
              height="64"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1"
            >
              <path
                d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5Z"
              />
              <path d="M12 5L8 21l4-7 4 7-4-16Z" />
            </svg>
            <p>暂无车辆信息</p>
            <button @click="showAddVehicleModal = true" class="add-button">
              添加第一辆车
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick } from "vue";
import { useVehicleStore } from "@/stores/vehicle";
import type {
  VehicleResponse,
  VehicleCreate,
  VehicleUpdate,
  VehicleFuelRecordResponse,
  VehicleFuelRecordCreate,
  VehicleFuelRecordUpdate,
  VehicleWithFuelStats,
  FuelConsumptionStats,
  VehicleFuelRecordListParams,
  FuelConsumptionStatsParams,
} from "@/types/vehicle";

// 车辆store
const vehicleStore = useVehicleStore();

// 标签页配置
const tabs = [
  { id: "records", label: "加油记录", icon: "⛽" },
];

// 响应式状态
const activeTab = ref("records");
const showDetailedStats = ref(false);
const vehicles = ref<VehicleResponse[]>([]);
const fuelRecords = ref<VehicleFuelRecordResponse[]>([]);
const gasStationTypes = ref<string[]>([]);
const vehiclesWithStats = ref<VehicleWithFuelStats[]>([]);
const fuelStats = ref<FuelConsumptionStats | null>(null);
const costSummary = ref<{
  total_cost?: number;
  monthly_average?: number;
  daily_average?: number;
} | null>(null);
const loading = ref(false);
const statsLoading = ref(false);

// 模态框状态
const showAddVehicleModal = ref(false);
const showEditVehicleModal = ref(false);
const showVehicleManagementModal = ref(false);
const showAddRecordModal = ref(false);
const showEditRecordModal = ref(false);
const showDeleteModal = ref(false);
const deleteTarget = ref<"vehicle" | "record">("vehicle");
const deleteTargetName = ref("");
const vehicleToDelete = ref<VehicleResponse | null>(null);
const recordToDelete = ref<VehicleFuelRecordResponse | null>(null);
const currentEditingVehicleId = ref<number | null>(null);
const currentEditingRecordId = ref<number | null>(null);

// 筛选条件
const filters = reactive<VehicleFuelRecordListParams>({
  vehicle_id: undefined,
  gas_station_type: undefined,
  start_date: undefined,
  end_date: undefined,
});

const statsFilters = reactive<FuelConsumptionStatsParams>({
  vehicle_id: undefined,
  start_date: undefined,
  end_date: undefined,
});

// 表单数据
const vehicleFormData = reactive<Partial<VehicleCreate & VehicleUpdate>>({
  name: "",
  brand: "",
  model: "",
  license_plate: "",
  year: undefined,
  is_active: true,
  notes: undefined,
});

const recordFormData = reactive<
  Partial<VehicleFuelRecordCreate & VehicleFuelRecordUpdate>
>({
  vehicle_id: undefined,
  current_mileage: undefined,
  fuel_amount: undefined,
  fuel_cost: undefined,
  fuel_price: undefined,
  gas_station_type: undefined,
  refuel_date: undefined,
  notes: undefined,
});

// 表单错误
const vehicleErrors = ref<Record<string, string>>({});
const recordErrors = ref<Record<string, string>>({});

// 计算属性
const totalFuelAmount = computed(() =>
  fuelRecords.value.reduce((sum, record) => sum + record.fuel_amount, 0),
);

const totalFuelCost = computed(() =>
  fuelRecords.value.reduce((sum, record) => sum + record.fuel_cost, 0),
);

const avgFuelConsumption = computed(() => {
  const validRecords = fuelRecords.value.filter(
    (r) => r.fuel_consumption !== null && r.fuel_consumption !== undefined,
  );
  if (validRecords.length === 0) return 0;
  return (
    validRecords.reduce((sum, record) => sum + record.fuel_consumption!, 0) /
    validRecords.length
  );
});

// 加油站常见固定金额对应的油量升数（基于常见油价）
const FUEL_AMOUNT_PRESETS = {
  100: { min: 13.0, max: 14.5 }, // 100元对应约13-14.5升
  200: { min: 26.0, max: 29.0 }, // 200元对应约26-29升
  300: { min: 39.0, max: 43.5 }, // 300元对应约39-43.5升
  400: { min: 52.0, max: 58.0 }, // 400元对应约52-58升
  500: { min: 65.0, max: 72.5 }, // 500元对应约65-72.5升
};

// 根据固定金额计算合适的油量（模拟加油站取舍逻辑）
const calculateFuelAmountFromCost = (cost: number, price: number): number => {
  const exactAmount = cost / price;

  // 检查是否为常见固定金额
  for (const [presetCost, range] of Object.entries(FUEL_AMOUNT_PRESETS)) {
    if (Math.abs(cost - Number(presetCost)) < 1) {
      // 允许1元误差
      // 在预设范围内选择最接近精确计算的值
      const clampedAmount = Math.max(
        range.min,
        Math.min(range.max, exactAmount),
      );
      return Math.round(clampedAmount * 100) / 100; // 保留两位小数
    }
  }

  // 非固定金额，正常计算并保留两位小数
  return Math.round(exactAmount * 100) / 100;
};

// 自动计算加油记录的三个字段
const calculateFuelRecord = (
  changedField: "fuel_amount" | "fuel_cost" | "fuel_price",
  fuelAmount: number | undefined,
  fuelCost: number | undefined,
  fuelPrice: number | undefined,
): { fuel_amount: number; fuel_cost: number; fuel_price: number } | null => {
  // 确保至少有两个有效值
  const validValues = [
    { key: "fuel_amount", value: fuelAmount },
    { key: "fuel_cost", value: fuelCost },
    { key: "fuel_price", value: fuelPrice },
  ].filter((item) => item.value !== undefined && item.value > 0);

  if (validValues.length < 2) {
    return null;
  }

  const values = validValues.reduce(
    (acc, item) => {
      acc[item.key] = item.value!;
      return acc;
    },
    {} as Record<string, number>,
  );

  let result: { fuel_amount: number; fuel_cost: number; fuel_price: number };

  switch (changedField) {
    case "fuel_amount":
      // 加油量变化，计算加油金额
      if (values.fuel_price) {
        result = {
          fuel_amount: values.fuel_amount,
          fuel_cost:
            Math.round(values.fuel_amount * values.fuel_price * 100) / 100,
          fuel_price: values.fuel_price,
        };
      } else if (values.fuel_cost) {
        result = {
          fuel_amount: values.fuel_amount,
          fuel_cost: values.fuel_cost,
          fuel_price:
            Math.round((values.fuel_cost / values.fuel_amount) * 100) / 100,
        };
      }
      break;

    case "fuel_cost":
      // 加油金额变化，计算加油量或油价
      if (values.fuel_price) {
        const calculatedAmount = calculateFuelAmountFromCost(
          values.fuel_cost,
          values.fuel_price,
        );
        result = {
          fuel_amount: calculatedAmount,
          fuel_cost: values.fuel_cost,
          fuel_price: values.fuel_price,
        };
      } else if (values.fuel_amount) {
        result = {
          fuel_amount: values.fuel_amount,
          fuel_cost: values.fuel_cost,
          fuel_price:
            Math.round((values.fuel_cost / values.fuel_amount) * 100) / 100,
        };
      }
      break;

    case "fuel_price":
      // 油价变化，计算加油金额
      if (values.fuel_amount) {
        result = {
          fuel_amount: values.fuel_amount,
          fuel_cost:
            Math.round(values.fuel_amount * values.fuel_price * 100) / 100,
          fuel_price: values.fuel_price,
        };
      } else if (values.fuel_cost) {
        const calculatedAmount = calculateFuelAmountFromCost(
          values.fuel_cost,
          values.fuel_price,
        );
        result = {
          fuel_amount: calculatedAmount,
          fuel_cost: values.fuel_cost,
          fuel_price: values.fuel_price,
        };
      }
      break;
  }

  return result!;
};

// 监听表单数据变化并自动计算
let isCalculating = false;

const handleFuelAmountChange = async (value: string) => {
  if (isCalculating) return;

  const numValue = value ? parseFloat(value) : undefined;
  if (!numValue || numValue <= 0) return;

  isCalculating = true;
  await nextTick();

  const result = calculateFuelRecord(
    "fuel_amount",
    numValue,
    recordFormData.fuel_cost,
    recordFormData.fuel_price,
  );
  if (result) {
    Object.assign(recordFormData, {
      fuel_amount: result.fuel_amount,
      fuel_cost: result.fuel_cost,
      fuel_price: result.fuel_price,
    });
  }

  setTimeout(() => {
    isCalculating = false;
  }, 50);
};

const handleFuelCostChange = async (value: string) => {
  if (isCalculating) return;

  const numValue = value ? parseFloat(value) : undefined;
  if (!numValue || numValue <= 0) return;

  isCalculating = true;
  await nextTick();

  const result = calculateFuelRecord(
    "fuel_cost",
    recordFormData.fuel_amount,
    numValue,
    recordFormData.fuel_price,
  );
  if (result) {
    Object.assign(recordFormData, {
      fuel_amount: result.fuel_amount,
      fuel_cost: result.fuel_cost,
      fuel_price: result.fuel_price,
    });
  }

  setTimeout(() => {
    isCalculating = false;
  }, 50);
};

const handleFuelPriceChange = async (value: string) => {
  if (isCalculating) return;

  const numValue = value ? parseFloat(value) : undefined;
  if (!numValue || numValue <= 0) return;

  isCalculating = true;
  await nextTick();

  const result = calculateFuelRecord(
    "fuel_price",
    recordFormData.fuel_amount,
    recordFormData.fuel_cost,
    numValue,
  );
  if (result) {
    Object.assign(recordFormData, {
      fuel_amount: result.fuel_amount,
      fuel_cost: result.fuel_cost,
      fuel_price: result.fuel_price,
    });
  }

  setTimeout(() => {
    isCalculating = false;
  }, 50);
};

// 清除错误
const clearVehicleErrors = () => {
  vehicleErrors.value = {};
};

const clearRecordErrors = () => {
  recordErrors.value = {};
};

// 清除表单
const clearVehicleForm = () => {
  currentEditingVehicleId.value = null;
  Object.assign(vehicleFormData, {
    name: "",
    brand: "",
    model: "",
    license_plate: "",
    year: undefined,
    is_active: true,
    notes: undefined,
  });
  clearVehicleErrors();
};

const clearRecordForm = () => {
  currentEditingRecordId.value = null;
  Object.assign(recordFormData, {
    vehicle_id: undefined,
    current_mileage: undefined,
    fuel_amount: undefined,
    fuel_cost: undefined,
    fuel_price: undefined,
    gas_station_type: undefined,
    refuel_date: new Date().toISOString().slice(0, 16),
    notes: undefined,
  });
  clearRecordErrors();
};

// 获取车辆列表
const fetchVehicles = async () => {
  try {
    const response = await vehicleStore.fetchVehicles();
    vehicles.value = response.vehicles;
  } catch (error) {
    console.error("获取车辆列表失败:", error);
  }
};

// 获取加油站类型
const fetchGasStationTypes = async () => {
  try {
    gasStationTypes.value = await vehicleStore.fetchGasStationTypes();
  } catch (error) {
    console.error("获取加油站类型失败:", error);
  }
};

// 获取加油记录
const fetchRecords = async () => {
  try {
    loading.value = true;
    const response = await vehicleStore.fetchFuelRecords(filters);
    fuelRecords.value = response.fuel_records;
  } catch (error) {
    console.error("获取加油记录失败:", error);
  } finally {
    loading.value = false;
  }
};

// 获取带统计的车辆列表
const fetchVehiclesWithStats = async () => {
  try {
    vehiclesWithStats.value = await vehicleStore.fetchVehiclesWithStats();
  } catch (error) {
    console.error("获取车辆统计列表失败:", error);
  }
};

// 获取油耗统计
const fetchStats = async () => {
  try {
    statsLoading.value = true;
    fuelStats.value = await vehicleStore.fetchFuelStats(statsFilters);

    // 获取费用汇总
    const costFilters = {
      start_date: statsFilters.start_date || undefined,
      end_date: statsFilters.end_date || undefined,
      vehicle_id: statsFilters.vehicle_id || undefined,
    };
    costSummary.value = await vehicleStore.fetchFuelCostSummary(costFilters);
  } catch (error) {
    console.error("获取油耗统计失败:", error);
  } finally {
    statsLoading.value = false;
  }
};

// 车辆管理方法
const editVehicle = (vehicle: VehicleResponse) => {
  currentEditingVehicleId.value = vehicle.id;
  Object.assign(vehicleFormData, {
    name: vehicle.name,
    brand: vehicle.brand,
    model: vehicle.model,
    license_plate: vehicle.license_plate,
    year: vehicle.year,
    is_active: vehicle.is_active,
    notes: vehicle.notes,
  });
  showEditVehicleModal.value = true;
};

const deleteVehicle = (vehicle: VehicleResponse) => {
  vehicleToDelete.value = vehicle;
  deleteTarget.value = "vehicle";
  deleteTargetName.value = vehicle.name;
  showDeleteModal.value = true;
};

// 加油记录管理方法
const editRecord = (record: VehicleFuelRecordResponse) => {
  currentEditingRecordId.value = record.id;
  Object.assign(recordFormData, {
    vehicle_id: record.vehicle_id,
    current_mileage: record.current_mileage,
    fuel_amount: record.fuel_amount,
    fuel_cost: record.fuel_cost,
    fuel_price: record.fuel_price,
    gas_station_type: record.gas_station_type,
    refuel_date: new Date(record.refuel_date).toISOString().slice(0, 16),
    notes: record.notes,
  });
  showEditRecordModal.value = true;
};

const deleteRecord = (record: VehicleFuelRecordResponse) => {
  recordToDelete.value = record;
  deleteTarget.value = "record";
  deleteTargetName.value = `${record.vehicle_name} - ${formatDate(record.refuel_date)}`;
  showDeleteModal.value = true;
};

// 确认删除
const confirmDelete = async () => {
  try {
    loading.value = true;

    if (deleteTarget.value === "vehicle" && vehicleToDelete.value) {
      await vehicleStore.deleteVehicle(vehicleToDelete.value.id);
      vehicles.value = vehicles.value.filter(
        (v) => v.id !== vehicleToDelete.value!.id,
      );
    } else if (deleteTarget.value === "record" && recordToDelete.value) {
      await vehicleStore.deleteFuelRecord(recordToDelete.value.id);
      await fetchRecords();
      await fetchStats();
    }

    showDeleteModal.value = false;
    vehicleToDelete.value = null;
    recordToDelete.value = null;
  } catch (error) {
    console.error("删除失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理车辆表单提交
const handleVehicleSubmit = async () => {
  clearVehicleErrors();

  // 表单验证
  if (!vehicleFormData.name) {
    vehicleErrors.value.name = "请输入车辆名称";
    return;
  }
  if (!vehicleFormData.brand) {
    vehicleErrors.value.brand = "请输入车辆品牌";
    return;
  }
  if (!vehicleFormData.model) {
    vehicleErrors.value.model = "请输入车辆型号";
    return;
  }
  if (!vehicleFormData.license_plate) {
    vehicleErrors.value.license_plate = "请输入车牌号";
    return;
  }

  try {
    loading.value = true;

    if (showAddVehicleModal.value) {
      // 创建车辆
      const newVehicle = await vehicleStore.createVehicle(
        vehicleFormData as VehicleCreate,
      );
      vehicles.value.push(newVehicle);
    } else {
      // 更新车辆
      const updatedVehicle = await vehicleStore.updateVehicle(
        currentEditingVehicleId.value!,
        vehicleFormData as VehicleUpdate,
      );
      const index = vehicles.value.findIndex(
        (v) => v.id === currentEditingVehicleId.value,
      );
      if (index !== -1) {
        vehicles.value[index] = updatedVehicle;
      }
    }

    closeVehicleModals();
    await fetchVehiclesWithStats();
  } catch (error) {
    console.error("保存车辆失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理记录表单提交
const handleRecordSubmit = async () => {
  clearRecordErrors();

  // 表单验证
  if (!recordFormData.vehicle_id) {
    recordErrors.value.vehicle_id = "请选择车辆";
    return;
  }
  if (!recordFormData.current_mileage || recordFormData.current_mileage <= 0) {
    recordErrors.value.current_mileage = "请输入有效的里程数";
    return;
  }
  if (!recordFormData.fuel_amount || recordFormData.fuel_amount <= 0) {
    recordErrors.value.fuel_amount = "请输入有效的加油量";
    return;
  }
  if (!recordFormData.fuel_cost || recordFormData.fuel_cost <= 0) {
    recordErrors.value.fuel_cost = "请输入有效的加油金额";
    return;
  }
  if (!recordFormData.fuel_price || recordFormData.fuel_price <= 0) {
    recordErrors.value.fuel_price = "请输入有效的油价";
    return;
  }
  if (!recordFormData.gas_station_type) {
    recordErrors.value.gas_station_type = "请选择加油站类型";
    return;
  }
  if (!recordFormData.refuel_date) {
    recordErrors.value.refuel_date = "请选择加油日期";
    return;
  }

  try {
    loading.value = true;

    if (showAddRecordModal.value) {
      // 创建记录
      await vehicleStore.createFuelRecord(
        recordFormData as VehicleFuelRecordCreate,
      );
    } else {
      // 更新记录
      await vehicleStore.updateFuelRecord(
        currentEditingRecordId.value!,
        recordFormData as VehicleFuelRecordUpdate,
      );
    }

    await fetchRecords();
    await fetchStats();
    closeRecordModals();
  } catch (error) {
    console.error("保存加油记录失败:", error);
  } finally {
    loading.value = false;
  }
};

// 关闭模态框
const closeVehicleModals = () => {
  showAddVehicleModal.value = false;
  showEditVehicleModal.value = false;
  clearVehicleForm();
};

const closeRecordModals = () => {
  showAddRecordModal.value = false;
  showEditRecordModal.value = false;
  clearRecordForm();
};

// 格式化日期
const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleString("zh-CN");
};

// 设置默认日期范围（最近30天）
const setDefaultDateRange = () => {
  const endDate = new Date();
  const startDate = new Date();
  startDate.setDate(endDate.getDate() - 30);

  filters.end_date = endDate.toISOString().split("T")[0];
  filters.start_date = startDate.toISOString().split("T")[0];

  statsFilters.end_date = endDate.toISOString().split("T")[0];
  statsFilters.start_date = startDate.toISOString().split("T")[0];
};

// 监听详细统计展开状态
watch(showDetailedStats, async (isExpanded) => {
  if (isExpanded) {
    await fetchStats();
    await fetchVehiclesWithStats();
  }
});

// 组件挂载时获取数据
onMounted(async () => {
  setDefaultDateRange();
  await Promise.all([fetchVehicles(), fetchGasStationTypes(), fetchRecords()]);
});
</script>

<style scoped lang="scss">
.unified-fuel-management {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

// 油耗统计部分样式
.fuel-stats-section {
  margin-bottom: 32px;
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  padding: 24px;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h3 {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
    
    .manage-vehicles-btn {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 16px;
      background: var(--el-color-primary);
      color: white;
      border: none;
      border-radius: var(--el-border-radius-small);
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        background: var(--el-color-primary-light-3);
        transform: translateY(-1px);
      }
    }
  }
  
  .stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 16px;
  }
}

// 标签页样式
.tabs-container {
  margin-bottom: 24px;
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  padding: 8px;
}

.tabs {
  display: flex;
  gap: 8px;
}

.tab-button {
  flex: 1;
  padding: 12px 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: transparent;
  color: var(--el-text-color-secondary);
  border: none;
  border-radius: var(--el-border-radius-small);
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;

  &:hover {
    background: var(--el-bg-color-overlay);
    color: var(--el-text-color-primary);
  }

  &.active {
    background: var(--el-color-primary);
    color: white;

    &:hover {
      background: var(--el-color-primary-light-3);
    }
  }
}

.tab-icon {
  font-size: 18px;
}

.tab-label {
  font-size: 14px;
  font-weight: 500;
}

.tab-content {
  min-height: 400px;
}

// 车辆管理样式
.vehicles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.vehicle-card {
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  padding: 20px;
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    border-color: var(--el-border-color-light);
  }

  &.inactive {
    opacity: 0.6;
  }
}

.vehicle-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.vehicle-info {
  flex: 1;
}

.vehicle-name {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.vehicle-model {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.vehicle-badges {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.license-plate {
  background: var(--el-color-primary);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.year-badge {
  background: var(--el-bg-color-overlay);
  color: var(--el-text-color-secondary);
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;

  &.active {
    background: var(--el-color-success);
    color: white;
  }

  &.inactive {
    background: var(--el-color-warning);
    color: white;
  }
}

.vehicle-actions {
  display: flex;
  gap: 8px;
}

.action-button {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  color: var(--el-text-color-primary);
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  cursor: pointer;
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;

  &.edit {
    background: var(--el-color-primary);
    color: white;

    &:hover {
      background: color-mix(in srgb, var(--el-color-primary) 80%, black);
    }
  }

  &.delete {
    background: var(--el-color-danger);
    color: white;

    &:hover {
      background: color-mix(in srgb, var(--el-color-danger) 80%, black);
    }
  }
}

.vehicle-details {
  border-top: 1px solid var(--el-border-color);
  padding-top: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;

  &:last-child {
    margin-bottom: 0;
  }
}

.detail-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  min-width: 80px;
  margin-right: 8px;
}

.detail-value {
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.add-vehicle-card {
  border: 2px dashed var(--el-border-color);
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    border-color: var(--el-color-primary);
    background: var(--el-bg-color-overlay);
  }
}

.add-vehicle-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: var(--el-text-color-secondary);
}

.add-vehicle-text {
  font-size: 16px;
  font-weight: 500;
}

// 加油记录样式
.filter-section {
  margin-bottom: 24px;
  padding: 20px;
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border: 1px solid var(--el-border-color);
  border-radius: 12px;
}

.filter-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.filter-group {
  label {
    display: block;
    margin-bottom: 6px;
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  select,
  input {
    background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  color: var(--el-text-color-primary);
  font-size: 14px;
  padding: 8px 16px;
  outline: none;
  transition: all 0.3s ease;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;

    &:focus {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
  }

    &::placeholder {
    color: var(--el-text-color-placeholder);
  }
    width: 100%;
  }
}


.stat-card {
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border: 1px solid var(--el-border-color);
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    border-color: var(--el-border-color-light);
  }

  &.primary {
    border-left: 4px solid var(--el-color-primary);
  }

  &.success {
    border-left: 4px solid var(--el-color-success);
  }

  &.info {
    border-left: 4px solid var(--el-color-primary);
  }

  &.warning {
    border-left: 4px solid var(--el-color-warning);
  }
}

.stat-icon {
  font-size: 24px;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--el-bg-color-overlay);
  border-radius: 12px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);

  .unit {
    font-size: 14px;
    font-weight: 400;
    color: var(--el-text-color-secondary);
    margin-left: 4px;
  }
}

.records-section {
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border: 1px solid var(--el-border-color);
  border-radius: 12px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.add-button {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  color: var(--el-text-color-primary);
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  cursor: pointer;
  background: var(--el-color-primary);
  color: white;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  gap: 8px;

  &:hover {
    background: color-mix(in srgb, var(--el-color-primary) 80%, black);
  }
}

.loading-state {
  text-align: center;
  padding: 40px;
  color: var(--el-text-color-secondary);

  .loading-spinner {
    width: 40px;
    height: 40px;
    margin: 0 auto 16px;
    border: 3px solid var(--el-border-color);
    border-top: 3px solid var(--el-color-primary);
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--el-text-color-secondary);

  svg {
    margin-bottom: 16px;
    opacity: 0.5;
  }

  p {
    margin-bottom: 20px;
    font-size: 16px;
  }

  .empty-hint {
    font-size: 14px;
    opacity: 0.8;
  }
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.record-card {
  background: var(--el-bg-color-overlay);
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;

  &:hover {
    background: var(--el-bg-color);
  }
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.record-vehicle {
  flex: 1;
}

.vehicle-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.record-date {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.record-details {
  border-top: 1px solid var(--el-border-color);
  padding-top: 16px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
  margin-bottom: 12px;
}

.record-notes {
  display: flex;
  align-items: flex-start;
  gap: 8px;

  .detail-label {
    margin-bottom: 0;
    margin-top: 2px;
  }

  .detail-value {
    flex: 1;
    font-weight: normal;
  }
}

// 油耗统计样式
.main-stats {
  margin-bottom: 32px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 16px;

  &.secondary {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
}

.cost-summary-section {
  margin-bottom: 32px;
  padding: 24px;
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border: 1px solid var(--el-border-color);
  border-radius: 12px;

  h3 {
    margin: 0 0 20px 0;
    font-size: 20px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.cost-summary-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: var(--el-bg-color-overlay);
  border-radius: 8px;

  .cost-label {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }

  .cost-value {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.vehicle-comparison-section {
  margin-bottom: 32px;

  h3 {
    margin: 0 0 20px 0;
    font-size: 20px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.vehicle-comparison-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.vehicle-comparison-card {
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border: 1px solid var(--el-border-color);
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    border-color: var(--el-border-color-light);
  }
}

.vehicle-stats {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
  margin-bottom: 16px;
}

.vehicle-stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: var(--el-bg-color-overlay);
  border-radius: 6px;

  .stat-label {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }

  .stat-value {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }
}

.latest-record {
  border-top: 1px solid var(--el-border-color);
  padding-top: 16px;

  .latest-record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .latest-label {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }

    .latest-date {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }

  .latest-record-details {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      font-size: 13px;
      color: var(--el-text-color-primary);
      font-weight: 500;
    }
  }
}

.trend-section {
  margin-bottom: 32px;

  h3 {
    margin: 0 0 20px 0;
    font-size: 20px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.trend-chart {
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border: 1px solid var(--el-border-color);
  border-radius: 12px;
  padding: 20px;
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

// 模态框样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: var(--el-bg-color-overlay);
  border-radius: 16px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color);

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.close-button {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  color: var(--el-text-color-primary);
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  cursor: pointer;
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  color: var(--el-text-color-secondary);

  &:hover {
    background: var(--el-bg-color-overlay);
  }
}

.vehicle-form,
.record-form {
  padding: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-group {
  margin-bottom: 16px;

  label {
    display: block;
    margin-bottom: 6px;
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  input,
  textarea,
  select {
    background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  color: var(--el-text-color-primary);
  font-size: 14px;
  padding: 8px 16px;
  outline: none;
  transition: all 0.3s ease;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;

    &:focus {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
  }

    &::placeholder {
    color: var(--el-text-color-placeholder);
  }
    width: 100%;
  }

  textarea {
    resize: vertical;
    min-height: 80px;
  }
}

.error-message {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: var(--el-color-danger);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.cancel-button {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  color: var(--el-text-color-primary);
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  cursor: pointer;
  background: transparent;
  color: var(--el-text-color-secondary);
  border: 1px solid var(--el-border-color);

  &:hover {
    background: var(--el-bg-color-overlay);
  }
}

.submit-button {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  color: var(--el-text-color-primary);
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  cursor: pointer;
  background: var(--el-color-primary);
  color: white;

  &:hover {
    background: color-mix(in srgb, var(--el-color-primary) 80%, black);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

// 删除确认对话框
.delete-modal {
  max-width: 400px;
}

.delete-content {
  text-align: center;
  padding: 20px;

  svg {
    margin-bottom: 16px;
    color: var(--el-color-warning);
  }

  p {
    margin: 0 0 8px 0;
    font-size: 16px;
    color: var(--el-text-color-primary);
  }

  .delete-warning {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.delete-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0 20px 20px;
}

.delete-button {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  color: var(--el-text-color-primary);
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  cursor: pointer;
  background: var(--el-color-danger);
  color: white;

  &:hover {
    background: color-mix(in srgb, var(--el-color-danger) 80%, black);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

// 详细统计折叠区域样式
.detailed-stats-section {
  margin-bottom: 32px;
  background: var(--el-bg-color-overlay);
  backdrop-filter: blur(10px);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  overflow: hidden;
}

.collapsible-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  cursor: pointer;
  user-select: none;
  transition: all 0.3s ease;
  background: var(--el-bg-color-overlay);
  
  &:hover {
    background: var(--el-bg-color);
  }
  
  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
  
  .collapse-toggle {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .toggle-text {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      font-weight: 500;
    }
    
    .collapse-icon {
      transition: transform 0.3s ease;
      color: var(--el-text-color-secondary);
      
      &.collapsed {
        transform: rotate(-90deg);
      }
    }
  }
}

.detailed-stats-content {
  padding: 0 24px 24px;
  border-top: 1px solid var(--el-border-color);
  
  .filter-section {
    margin: 24px 0;
    padding: 20px;
    background: var(--el-bg-color);
    backdrop-filter: blur(10px);
    border: 1px solid var(--el-border-color);
    border-radius: 12px;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .unified-fuel-management {
    padding: 16px;
  }
  
  .vehicles-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
  
  .vehicle-comparison-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }
}

@media (max-width: 992px) {
  .unified-fuel-management {
    padding: 12px;
  }
  
  .stats-cards {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
  
  .filter-row {
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  }
}

@media (max-width: 768px) {
  .unified-fuel-management {
    padding: 8px;
  }

  .tabs {
    flex-direction: column;
  }

  .tab-button {
    justify-content: flex-start;
    padding: 10px 16px;
  }

  .vehicles-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .filter-row {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .detail-grid {
    grid-template-columns: 1fr;
  }

  .form-row {
    grid-template-columns: 1fr;
  }

  .section-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .record-header {
    flex-direction: column;
    gap: 12px;
  }

  .record-actions {
    align-self: flex-end;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .cost-summary-grid {
    grid-template-columns: 1fr;
  }

  .vehicle-comparison-grid {
    grid-template-columns: 1fr;
  }

  .vehicle-stats {
    grid-template-columns: 1fr;
  }

  .latest-record-details {
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;
  }
  
  .modal {
    width: 95%;
    max-width: none;
    max-height: 95vh;
  }
  
  .vehicle-management-modal {
    width: 95%;
    max-width: none;
  }
}

@media (max-width: 480px) {
  .unified-fuel-management {
    padding: 4px;
  }

  .fuel-stats-section {
    padding: 16px;
    margin-bottom: 16px;
  }

  .tabs-container {
    padding: 4px;
    margin-bottom: 16px;
  }

  .filter-section {
    padding: 12px;
    margin-bottom: 16px;
  }

  .records-section {
    padding: 12px;
  }

  .vehicle-card {
    padding: 12px;
  }

  .record-card {
    padding: 12px;
  }

  .stat-card {
    padding: 12px;
  }

  .modal {
    width: 98%;
    border-radius: var(--el-border-radius-small);
  }
  
  .modal-header {
    padding: 12px 16px;
    
    h3 {
      font-size: 16px;
    }
  }
  
  .vehicle-form,
  .record-form {
    padding: 12px 16px;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 8px;
  }
}

@media (max-height: 600px) {
  .unified-fuel-management {
    padding: 8px;
  }
  
  .fuel-stats-section {
    padding: 12px;
    margin-bottom: 12px;
  }
  
  .tabs-container {
    margin-bottom: 12px;
  }
  
  .filter-section {
    padding: 8px;
    margin-bottom: 12px;
  }
  
  .records-section {
    padding: 8px;
  }
  
  .modal {
    max-height: 98vh;
  }
}

// 车辆管理弹窗样式
.vehicle-management-modal {
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  
  .vehicle-management-content {
    padding: 20px;
  }
  
  .vehicles-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    max-height: 400px;
    overflow-y: auto;
  }
  
  .vehicle-management-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    background: var(--el-bg-color);
    border: 1px solid var(--el-border-color);
    border-radius: var(--el-border-radius-base);
    transition: all 0.3s ease;
    
    &:hover {
      border-color: var(--el-color-primary);
      box-shadow: var(--el-box-shadow-light);
    }
    
    &.inactive {
      opacity: 0.6;
    }
    
    &.add-vehicle-item {
      cursor: pointer;
      border-style: dashed;
      background: var(--el-bg-color-overlay);
      
      &:hover {
        border-color: var(--el-color-primary);
        background: var(--el-color-primary-light-9);
      }
    }
  }
  
  .vehicle-info {
    flex: 1;
    
    .vehicle-name {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .vehicle-details {
      display: flex;
      align-items: center;
      gap: 12px;
      flex-wrap: wrap;
      
      .vehicle-model {
        font-size: 14px;
        color: var(--el-text-color-secondary);
      }
      
      .vehicle-license {
        font-size: 14px;
        color: var(--el-text-color-regular);
        background: var(--el-bg-color-overlay);
        padding: 2px 8px;
        border-radius: var(--el-border-radius-small);
      }
      
      .status-badge {
        font-size: 12px;
        padding: 2px 8px;
        border-radius: var(--el-border-radius-small);
        font-weight: 500;
        
        &.active {
          background: rgba(34, 197, 94, 0.1);
          color: #22c55e;
        }
        
        &.inactive {
          background: rgba(156, 163, 175, 0.1);
          color: #9ca3af;
        }
      }
    }
  }
  
  .vehicle-actions {
    display: flex;
    gap: 8px;
    
    .action-button {
      width: 32px;
      height: 32px;
      border: none;
      border-radius: var(--el-border-radius-small);
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
      
      &.edit {
        background: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
        
        &:hover {
          background: var(--el-color-primary-light-8);
        }
      }
      
      &.delete {
        background: rgba(239, 68, 68, 0.1);
        color: #ef4444;
        
        &:hover {
          background: rgba(239, 68, 68, 0.2);
        }
      }
    }
  }
  
  .add-vehicle-content {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    font-weight: 500;
  }
  
  .empty-state {
    text-align: center;
    padding: 40px 20px;
    color: var(--el-text-color-secondary);
    
    p {
      margin: 16px 0;
      font-size: 16px;
    }
    
    .add-button {
      margin-top: 16px;
    }
  }
}
</style>
